package com.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import com.mapper.WtdMapper;
import com.pojo.OUser;
import com.pojo.Statis;
import com.pojo.Wtd;
import com.service.TradeService;
import com.service.WtdService;
import com.mapper.GoodMapper;
import com.mapper.TradeMapper;
import com.mapper.UsersMapper;

@Controller
@RequestMapping("/")
public class WtdController {
	@Resource
	private WtdMapper wtdMapper;
	@Resource
	private UsersMapper usersMapper;
	@Resource
	private TradeMapper tradeMapper;
	@Resource
	private TradeService tradeService;
	@Resource
	private WtdService wtdService;
	@Resource
	private GoodMapper goodMapper;

	// 查询

	// public String selectprice(HttpServletRequest request, Model model, Wtd wt)
	// throws FileNotFoundException {
	//
	// return "jsp/jydtbuy";
	// }

	// 价格请求
	@RequestMapping("getprice")
	@ResponseBody
	public String getprice(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		OUser Ouser = (OUser) session.getAttribute("user");
		//System.out.println(Ouser.getUserID());
		String goods=(String) request.getParameter("goods");
		List<Map> list1 = wtdMapper.selectwtdprice(goods);
		List<Map> list2 = wtdMapper.selectwtdprice2(goods);
	    List<Map> list3=wtdMapper.selectwtdpricebuy(goods);
	    List<Map> list4=wtdMapper.selectwtdprice2sale(goods);
		List list = new ArrayList();
		if(Ouser.getUserID().equals("100000")) {
		  list.add(list1);
		  list.add(list2);
		  list.add(list3);
		  list.add(list4);
		}else {
			list.add(list1);
		    list.add(list2);
		}
		String str = JSON.toJSONString(list);
		//System.out.println(str);
		return str;

	}

	public static int belongCalendar(Date time, Date from, Date to) {
        Calendar date = Calendar.getInstance();
        date.setTime(time);

        Calendar after = Calendar.getInstance();
        after.setTime(from);

        Calendar before = Calendar.getInstance();
        before.setTime(to);

        if (date.after(before) || date.before(after)) {
            return 1;
        } else {
            return 0;
        }
    }
	public static int afterCalendar(Date time, Date to) {
        Calendar date = Calendar.getInstance();
        date.setTime(time);
        
        Calendar before = Calendar.getInstance();
        before.setTime(to);

        if (date.after(before) ) {
        	Date now = new Date();
        	SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
			String s2 = sdf.format(now);	
			
			if (s2.equals("星期六") || s2.equals("星期日")) {
				 return 1;
			}else {
				return 2;
			}
        } else {
            return 0;
        }
    }
	//Java Date与String的相互转换
	public static Date stringToDate(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");//日期格式
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

	// 添加委托单
		@RequestMapping("insertwtd")
		@ResponseBody
		public String insertwtd(HttpServletRequest request, Wtd wtd, Model model) {
		//	System.out.println(wtd.getGoods());
			Statis meiri = wtdMapper.selectmeiri(wtd.getGoods());//查询每日statis的开盘价
			request.setAttribute("meiri", meiri);
			HttpSession session = request.getSession();
		
			BigDecimal openprice = meiri.getOpenprice();
			OUser Ouser = (OUser) session.getAttribute("user");
			// 获取当前时间，作为委托单的提交时间
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = dateFormat.format(now);

			/*SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
			String s2 = sdf.format(now);
			
			if (s2.equals("星期六") || s2.equals("星期日")) {
				 
				return "untradedate";
			}*/
			
			Date from = stringToDate("2018-02-13");
	        Date to= stringToDate("2018-02-22");        
	        Date s3=stringToDate(time);        
	        int datetimes=belongCalendar(s3,from,to); 	        
	        if(datetimes==0) {
	        	return "untradeyear";
	        }	        
	        int datetimes1=afterCalendar(s3,to); 
	        if(datetimes1==1) {
	        	return "untradedate";
	        }
	        
	        /*if (date.after(before) || date.before(after)) {
	            return 1;
	        }*/
			
			// 插入委托单
			HashMap<String, Object> tests = new HashMap<String, Object>();
			tests.put("UserID", Ouser.getUserID());
			tests.put("ttype", wtd.getTtype());
			tests.put("wcount", wtd.getWcount());
			tests.put("wprice", wtd.getWprice());

			/* 调试价格在指导价的上下百分之十 2017/12/1 11:33 yy */
			if (wtd.getWprice().floatValue() > openprice.floatValue() * 1.1
					|| wtd.getWprice().floatValue() < openprice.floatValue() * 0.9) {
				return "priceerror";

			}
			tests.put("consume", wtd.getConsume());
			tests.put("goods", wtd.getGoods());
			tests.put("wtime", time);
			tests.put("tcount", 0);
			
			
		

			if (tests.get("ttype").equals("买")) {
				// 获得当前用户的余额
				OUser u = usersMapper.selectmember(Ouser.getUserID());
				HashMap<String, Object> sss = new HashMap<String, Object>();
				sss.put("encash", u.getEncash());
				// 委托单上的总金额
				BigDecimal consume = (BigDecimal) tests.get("consume");		
				// 账户余额，即取现（积分）
				BigDecimal encash = (BigDecimal) sss.get("encash");
				//委托单加手续费
				BigDecimal wpfee=consume.add(consume.multiply(BigDecimal.valueOf(0.003)));
			
				if((wtdMapper.selectuserwtd(tests.get("UserID").toString()))==0) {//查看该用户是否有买单
					if(encash.compareTo(wpfee)<0) {//账户余额小于委托单需要花费的金额
						return "unencash";
					}else {
						try {
							SimpleDateFormat sim2 = new SimpleDateFormat("HH:mm:ss");
							Date date2 = sim2.parse(sim2.format(new Date()));
							//判断是否在交易时间段
							if ((date2.before(sim2.parse("11:30:00")) && date2.after(sim2.parse("09:30:00")))
									|| (date2.before(sim2.parse("15:00:00")) && date2.after(sim2.parse("13:00:00")))) {
								buy(tests);
							} else {
								return "untrade";
							}
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}else {
					//计算所有买单的总金额
					BigDecimal wtdzj=tradeMapper.selectsumconsume(tests.get("UserID").toString());
					BigDecimal zj=wtdzj.add(consume);
					BigDecimal zjfee=zj.add(zj.multiply(BigDecimal.valueOf(0.003)));
					
					 if(encash.compareTo(zjfee)<0){//账户余额小于全部委托单需要花费的金额
						return "unfinish";
					}else {
						try {
							SimpleDateFormat sim2 = new SimpleDateFormat("HH:mm:ss");
							Date date2 = sim2.parse(sim2.format(new Date()));
							if ((date2.before(sim2.parse("11:30:00")) && date2.after(sim2.parse("09:30:00")))
									|| (date2.before(sim2.parse("15:00:00")) && date2.after(sim2.parse("13:00:00")))) {
								buy(tests);
							} else {
								return "untrade";
							}
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}
			} else {
				//获得商品余量
				Wtd cgoodsmx = usersMapper.selectcgmx(tests);
				if(cgoodsmx==null)
					return "nogoods";
				HashMap<String, Object> sss1 = new HashMap<String, Object>();
				sss1.put("goodnum", cgoodsmx.getGoodnum());
				sss1.put("djgoodnum", cgoodsmx.getDjgoodnum());
				int wc = (int) tests.get("wcount");
				int gn = (int) sss1.get("goodnum");
				int djgn = (int) sss1.get("djgoodnum");
				int kygn = gn-djgn;
				
				int allgbobv=wtdMapper.selectgoodBankobv1(tests);// 查询商品是否有库存
				int obv;// 库存数量
				if (allgbobv == 0) {
					obv = 0;
				} else {
					obv = wtdMapper.selectgoodBankobv(tests);//查找库存总量
				}
				if(obv!=gn) {
					return "undangerous";
				}
				if(djgn<0) {
					return "djnumerror";
				}else if (wc > kygn) {
					return "unwcount";
				} else {
					try {
						SimpleDateFormat sim2 = new SimpleDateFormat("HH:mm:ss");
						Date date2 = sim2.parse(sim2.format(new Date()));
						if ((date2.before(sim2.parse("11:30:00")) && date2.after(sim2.parse("09:30:00")))
								|| (date2.before(sim2.parse("15:00:00")) && date2.after(sim2.parse("13:00:00")))) {
							sale(tests);
						} else {
							return "untrade";
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
			return "insertwtdok";
		}
//2017.12.9 9:11 yy 
	//2017.12.18 11:11 yy 添加事务处理
	public void buy(HashMap tests) {
		tradeService.insertbuy(tests);
	}

	//2017.12.18 11:11 yy 添加事务处理
	public void sale(HashMap tests) {
		tradeService.insertsale(tests);
	}

	// [][] [[],[]]
	// 查询委托单明细
	@RequestMapping(value = "selectwtdprice")
	public String selectwtdprice(HttpServletRequest request, Model model) {
		String goods = request.getParameter("goods");
		//System.out.println(goods);
		request.setAttribute("goods1", goods);
		Statis meiri = goodMapper.selectopenprice(goods);//查询每日statis的开盘价
		HashMap mp = new HashMap();
		goods="\""+goods+ "\"";
		mp.put("meiri", meiri);
		mp.put("goods", goods);
		request.setAttribute("map", mp);
		HttpSession session = request.getSession();
		OUser Ouser = (OUser) session.getAttribute("user");
		OUser user = usersMapper.selectmember(Ouser.getUserID());
		request.setAttribute("user", user);
		
		List list2 = wtdMapper.selectwtd(Ouser.getUserID());
		String list1 = JSON.toJSONString(list2);
		request.setAttribute("list1", list1);
		//查找商品类型
		List<Map> list=wtdMapper.selectgoodstype();
		//System.out.println("273"+JSON.toJSONString(list));
		request.setAttribute("list", list);
		return "jsp/jydtbuy";
	}

	@RequestMapping(value = "selectwtd")

	public void selectwtd(HttpServletRequest request, Model model, HttpServletResponse response) {
		String UserID = request.getParameter("UserID");
		PrintWriter out = null;
		response.setContentType("text/plain;charset=UTF-8");
		try {
			List list2 = wtdMapper.selectwtd(UserID);
			out = response.getWriter();
			out.write(JSON.toJSONString(list2));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}

	}

	// 撤单
	@RequestMapping("canclewtd")
	@ResponseBody
	public String canclewtd(HttpServletRequest request, Model mode, Wtd w) {
		HttpSession session = request.getSession();
		long wid = w.getWid();
		//////System.out.println(wid);
		Wtd wtd = wtdMapper.selectwtds(wid);
		//////System.out.println(wtd);
		HashMap<String, Object> tests = new HashMap<String, Object>();
		tests.put("tcount", wtd.getTcount());
		tests.put("wcount", wtd.getWcount());
		tests.put("UserID", wtd.getUserID());
		tests.put("goods", wtd.getGoods());
		tests.put("ttype", wtd.getTtype());
		tests.put("wid", wtd.getWid());
		wtdService.updatecxwtd(tests);
		return "ok";
	}
	
	//查询平台明细
		@RequestMapping(value = "selectplatmx")
		public void selectplatmx(HttpServletRequest request, Model model, HttpServletResponse response) {		
			PrintWriter out = null;
			response.setContentType("text/plain;charset=UTF-8");
			try {
				List platmx = tradeMapper.selectTratablemx();// 查询某用户的平台明细
				out = response.getWriter();
				out.write(JSON.toJSONString(platmx));
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				out.close();
			}

		}

}
